﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class Warehouse : Form
    {
        public string SelectedWarehouseName { get; private set; }
        public string SelectedStorageLocation { get; private set; }
        public string SelectedWarehouseArea { get; private set; }

        public Warehouse()
        {
            InitializeComponent();
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            InitializeDataGridView();
            GetData();
            
            // 绑定按钮事件
            btnsure.Click += Btnsure_Click;
            btnquxiao.Click += Btnquxiao_Click;
            
            // 设置窗体标题和属性
            this.Text = "选择仓库信息";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            // 设置按钮文本
            if (btnsure != null)
                btnsure.Text = "确定选择";
            if (btnquxiao != null)
                btnquxiao.Text = "取消";
            
            // 添加键盘事件
            this.KeyPreview = true;
            this.KeyDown += Warehouse_KeyDown;
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void Btnsure_Click(object sender, EventArgs e)
        {
            // 查找选中的行
            for (int i = 0; i < dgvware.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvware.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    // 获取选中行的数据
                    SelectedWarehouseName = dgvware.Rows[i].Cells[1].Value?.ToString() ?? ""; // 仓库名称
                    SelectedStorageLocation = dgvware.Rows[i].Cells[2].Value?.ToString() ?? ""; // 库位名称
                    SelectedWarehouseArea = dgvware.Rows[i].Cells[5].Value?.ToString() ?? ""; // 库区名称
                    
                    // 调试信息：显示获取到的数据
                    Console.WriteLine($"选中的仓库信息:");
                    Console.WriteLine($"  仓库名称: {SelectedWarehouseName}");
                    Console.WriteLine($"  库位名称: {SelectedStorageLocation}");
                    Console.WriteLine($"  库区名称: {SelectedWarehouseArea}");
                    
                    // 调试信息：显示所有列的数据
                    Console.WriteLine($"所有列的数据:");
                    for (int j = 0; j < dgvware.Columns.Count; j++)
                    {
                        var col = dgvware.Columns[j];
                        var value = dgvware.Rows[i].Cells[j].Value?.ToString() ?? "";
                        Console.WriteLine($"  列 {j} ({col.Name}): {value}");
                    }
                    
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
            }
            
            MessageBox.Show("请先选择一条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void Btnquxiao_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 获取选中的仓库项目
        /// </summary>
        /// <returns>选中的仓库项目列表</returns>
        public List<WarehouseOutput> GetSelectedItems()
        {
            var selectedItems = new List<WarehouseOutput>();
            
            for (int i = 0; i < dgvware.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvware.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    try
                    {
                        // 安全地获取单元格值
                        var warehouseIdValue = dgvware.Rows[i].Cells[3].Value;
                        var areaIdValue = dgvware.Rows[i].Cells[4].Value;
                        
                        // 调试信息：显示原始值
                        Console.WriteLine($"=== 仓库数据调试信息 ===");
                        Console.WriteLine($"行 {i} 仓库ID原始值: {warehouseIdValue} (类型: {warehouseIdValue?.GetType()})");
                        Console.WriteLine($"行 {i} 库区ID原始值: {areaIdValue} (类型: {areaIdValue?.GetType()})");
                        Console.WriteLine($"行 {i} 仓库名称: {dgvware.Rows[i].Cells[1].Value}");
                        Console.WriteLine($"行 {i} 库位名称: {dgvware.Rows[i].Cells[2].Value}");
                        Console.WriteLine($"行 {i} 库区名称: {dgvware.Rows[i].Cells[5].Value}");
                        Console.WriteLine("==================");
                        
                        // 获取选中行的数据
                        var warehouseOutput = new WarehouseOutput
                        {
                            WarehouseId = SafeConvertToInt32(warehouseIdValue), // 仓库ID列
                            Warehouse_Name = dgvware.Rows[i].Cells[1].Value?.ToString() ?? "", // 仓库名称列
                            Storage_location = dgvware.Rows[i].Cells[2].Value?.ToString() ?? "", // 库位名称列
                            AreaId = SafeConvertToInt32(areaIdValue), // 库区ID列
                            Warehouse_Area = dgvware.Rows[i].Cells[5].Value?.ToString() ?? "" // 库区名称列
                        };
                        
                        selectedItems.Add(warehouseOutput);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"处理第 {i} 行数据时发生错误: {ex.Message}");
                        // 继续处理下一行，不中断整个流程
                        continue;
                    }
                }
            }
            
            return selectedItems;
        }

        /// <summary>
        /// 安全地将对象转换为int32
        /// </summary>
        /// <param name="value">要转换的值</param>
        /// <returns>转换后的整数，如果转换失败返回1</returns>
        private int SafeConvertToInt32(object value)
        {
            try
            {
                if (value == null)
                    return 1;
                
                // 如果已经是整数类型，直接转换
                if (value is int intValue)
                    return intValue;
                if (value is long longValue)
                    return (int)longValue;
                if (value is short shortValue)
                    return shortValue;
                if (value is byte byteValue)
                    return byteValue;
                
                // 如果是字符串，尝试解析
                if (value is string stringValue)
                {
                    if (int.TryParse(stringValue, out int result))
                        return result;
                    else
                        return 1; // 解析失败返回默认值1
                }
                
                // 尝试直接转换
                return Convert.ToInt32(value);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"SafeConvertToInt32转换失败: {ex.Message}, 值: {value}");
                return 1; // 转换失败返回默认值1
            }
        }

        /// <summary>
        /// 初始化DataGridView，添加复选框列
        /// </summary>
        private void InitializeDataGridView()
        {
            // 清空现有列
            dgvware.Columns.Clear();
            
            // 添加复选框列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "选择";
            checkBoxColumn.Name = "CheckBoxColumn";
            checkBoxColumn.Width = 50;
            dgvware.Columns.Add(checkBoxColumn);
            
            // 添加仓库名称列
            DataGridViewTextBoxColumn warehouseNameColumn = new DataGridViewTextBoxColumn();
            warehouseNameColumn.HeaderText = "仓库名称";
            warehouseNameColumn.Name = "WarehouseNameColumn";
            warehouseNameColumn.DataPropertyName = "Warehouse_Name";
            warehouseNameColumn.Width = 150;
            dgvware.Columns.Add(warehouseNameColumn);
            
            // 添加库位名称列
            DataGridViewTextBoxColumn storageLocationColumn = new DataGridViewTextBoxColumn();
            storageLocationColumn.HeaderText = "库位名称";
            storageLocationColumn.Name = "StorageLocationColumn";
            storageLocationColumn.DataPropertyName = "Storage_location";
            storageLocationColumn.Width = 150;
            dgvware.Columns.Add(storageLocationColumn);
            
            // 添加仓库ID列（隐藏列，用于数据绑定）
            DataGridViewTextBoxColumn warehouseIdColumn = new DataGridViewTextBoxColumn();
            warehouseIdColumn.HeaderText = "仓库ID";
            warehouseIdColumn.Name = "WarehouseIdColumn";
            warehouseIdColumn.DataPropertyName = "WarehouseId";
            warehouseIdColumn.Width = 80;
            warehouseIdColumn.Visible = false; // 隐藏此列
            dgvware.Columns.Add(warehouseIdColumn);
            
            // 添加库区ID列（隐藏列，用于数据绑定）
            DataGridViewTextBoxColumn areaIdColumn = new DataGridViewTextBoxColumn();
            areaIdColumn.HeaderText = "库区ID";
            areaIdColumn.Name = "AreaIdColumn";
            areaIdColumn.DataPropertyName = "AreaId";
            areaIdColumn.Width = 80;
            areaIdColumn.Visible = false; // 隐藏此列
            dgvware.Columns.Add(areaIdColumn);
            
            // 添加库区名称列
            DataGridViewTextBoxColumn warehouseAreaColumn = new DataGridViewTextBoxColumn();
            warehouseAreaColumn.HeaderText = "库区名称";
            warehouseAreaColumn.Name = "WarehouseAreaColumn";
            warehouseAreaColumn.DataPropertyName = "Warehouse_Area";
            warehouseAreaColumn.Width = 150;
            dgvware.Columns.Add(warehouseAreaColumn);
            
            // 设置复选框列只能单选
            dgvware.CellClick += Dgvware_CellClick;
            
            // 添加双击行选择功能
            dgvware.CellDoubleClick += Dgvware_CellDoubleClick;
            
            // 设置DataGridView属性
            dgvware.AllowUserToAddRows = false;
            dgvware.AllowUserToDeleteRows = false;
            dgvware.ReadOnly = true;
            dgvware.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvware.MultiSelect = false;
            
            // 设置复选框列提示
            checkBoxColumn.ToolTipText = "点击选择仓库";
        }

        /// <summary>
        /// DataGridView单元格点击事件，实现单选功能
        /// </summary>
        private void Dgvware_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0) // 点击复选框列
            {
                // 取消其他行的选中状态
                for (int i = 0; i < dgvware.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        dgvware.Rows[i].Cells[0].Value = false;
                    }
                }
                
                // 设置当前行复选框状态
                bool currentValue = dgvware.Rows[e.RowIndex].Cells[0].Value == null ? false : (bool)dgvware.Rows[e.RowIndex].Cells[0].Value;
                dgvware.Rows[e.RowIndex].Cells[0].Value = !currentValue;
                
                // 更新状态栏显示选中的仓库信息
                UpdateStatusBar();
            }
        }
        
        /// <summary>
        /// DataGridView双击事件，快速选择仓库
        /// </summary>
        private void Dgvware_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex > 0) // 双击非复选框列
            {
                // 先选中当前行
                for (int i = 0; i < dgvware.Rows.Count; i++)
                {
                    dgvware.Rows[i].Cells[0].Value = (i == e.RowIndex);
                }
                
                // 自动点击确定按钮
                Btnsure_Click(sender, e);
            }
        }

        /// <summary>
        /// 更新状态栏显示选中的仓库信息
        /// </summary>
        private void UpdateStatusBar()
        {
            for (int i = 0; i < dgvware.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvware.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    string warehouseName = dgvware.Rows[i].Cells[1].Value?.ToString() ?? "";
                    string storageLocation = dgvware.Rows[i].Cells[2].Value?.ToString() ?? "";
                    string warehouseArea = dgvware.Rows[i].Cells[5].Value?.ToString() ?? "";
                    
                    string statusText = $"已选择: {warehouseName} - {warehouseArea} - {storageLocation}";
                    this.Text = $"选择仓库信息 - {statusText}";
                    return;
                }
            }
            
            // 没有选中任何仓库时，恢复默认标题
            this.Text = "选择仓库信息";
        }
        
        /// <summary>
        /// 键盘事件处理
        /// </summary>
        private void Warehouse_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    // 按回车键确认选择
                    Btnsure_Click(sender, e);
                    break;
                case Keys.Escape:
                    // 按ESC键取消
                    Btnquxiao_Click(sender, e);
                    break;
                case Keys.F1:
                    // 按F1键显示使用提示
                    ShowUsageTip();
                    break;
            }
        }
        
        /// <summary>
        /// 显示使用提示
        /// </summary>
        private void ShowUsageTip()
        {
            string tip = "使用说明：\n" +
                        "1. 点击复选框选择仓库\n" +
                        "2. 双击行可快速选择\n" +
                        "3. 点击确定按钮完成选择\n" +
                        "4. 点击取消按钮关闭窗口\n" +
                        "5. 按回车键确认选择\n" +
                        "6. 按ESC键取消选择";
            
            MessageBox.Show(tip, "使用提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 2;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;

        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }

        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<WarehouseOutput>>>(
                    endpoint: "Material/GetWarehousrsShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvware.DataSource = response.data;
                
                // 初始化复选框列的值
                foreach (DataGridViewRow row in dgvware.Rows)
                {
                    row.Cells[0].Value = false;
                }
                
                // 显示数据总数
                if (response.totalCount > 0)
                {
                    this.Text = $"选择仓库信息 - 共 {response.totalCount} 条记录";
                }
                
                // 调试信息：显示列的数据属性名称
                Console.WriteLine($"列数量: {dgvware.Columns.Count}");
                for (int i = 0; i < dgvware.Columns.Count; i++)
                {
                    var col = dgvware.Columns[i];
                    Console.WriteLine($"列 {i}: {col.Name} - {col.DataPropertyName} - {col.HeaderText}");
                }
                
                // 调试信息：显示第一行数据（如果存在）
                if (dgvware.Rows.Count > 0)
                {
                    Console.WriteLine($"第一行数据:");
                    for (int j = 0; j < dgvware.Columns.Count; j++)
                    {
                        var col = dgvware.Columns[j];
                        var value = dgvware.Rows[0].Cells[j].Value?.ToString() ?? "";
                        Console.WriteLine($"  列 {j} ({col.Name}): {value}");
                    }
                }
            }
        }
    }
}
